<template>
  <div class="map-page-container">
    <!-- :center="center" -->
    <el-amap
      ref="map"
      :zoom="zoom"
      :plugin="mapInfo.plugin"
      :events="mapInfo.events"
      :amap-manager="amapManager"
      v-show="isShow"
    >
    </el-amap>
  </div>
</template>

<script>
import { AMapManager } from "vue-amap";
let amapManager = new AMapManager();
export default {
  name: "Map",
  props: {
    data: {
      type: Array,
      default: () => [],
    },
    edit: {
      type: Boolean,
      default: true,
      require: false,
    },
    // 0:高德坐标 1:gps坐标
    type: {
      type: Number,
      default: 0,
      require: false,
    },
  },
  data() {
    const self = this;
    return {
      isShow: false,
      // amap
      amapManager,
      center: [120.069898, 30.322001],
      lng: "",
      lat: "",
      address: null,
      marker: "",
      zoom: 15,
      point: [],
      mapInfo: {
        map: null,
        navgtr: null, // 巡航器
        pathSimplifierIns: null, // 巡航轨迹路线
        plugin: [
          { pName: "OverView", isOpen: true },
          "Scale",
          "ToolBar",
          "CircleEditor",
          // {
          //   // 定位
          //   pName: "GeoloCation",
          //   events: {
          //     init(o) {
          //       // o 是高德地图定位插件实例
          //       o.getCurrentPosition((status, result) => {
          //         console.log(JSON.stringify(result));
          //         if (result && result.position) {
          //           self.lng = result.position.lng;
          //           self.lat = result.position.lat;
          //           self.address = result.formattedAddress;
          //           self.center = [self.lng, self.lat];
          //           let o = amapManager.getMap();
          //           if (!self.marker) {
          //             self.marker = new AMap.Marker({
          //               position: self.center,
          //             });
          //             self.marker.setMap(o);
          //           }
          //           self.marker.setPosition(self.center);
          //         } else {
          //           self.$message.error("位置信息，获取失败！");
          //         }
          //       });
          //     },
          //   },
          // },
        ],
        events: {
          init: (o) => {
            self.mapInfo.map = o;
            console.log(o, 2312312);
          },
          click(e) {
            self.point = [e.lnglat.getLng(), e.lnglat.getLat()];
          },
        },
      },

      // mouse-tool
      mouseTool: null,
      fenceForm: {
        coordinate: [],
        fenceData: {},
      },
      mousetoolType: null,
    };
  },
  watch: {
    data: {
      handler(val) {
        setTimeout(() => {
          this.isShow = true;
        }, 500);
        // this.addFence("polygon");
        // this.setLatLng();
      },
      deep: true,
    },
  },
  mounted() {
  },
  methods: {
    addFence(type) {
      let fenceData = {};
      this.mousetoolType = type;
      let _this = this;
      let map = amapManager.getMap();
      if (this.fenceForm.coordinate.length > 0) {
        this.$Message.error("围栏已存在!");
        return;
      }
      if (this.mousetoolType) {
        map.remove(this.mousetoolType);
      }
      map.plugin(["AMap.MouseTool"], function () {
        let mouseTool = new AMap.MouseTool(map);
        _this.mouseTool = mouseTool;
        //添加事件
        if (type === "circle") {
          mouseTool.circle();
          AMap.event.addListener(mouseTool, "draw", function (e) {
            _this.fenceForm.coordinate = [];
            let path = e.obj.getPath();
            path.forEach((e) => {
              _this.fenceForm.coordinate.push([e.getLng(), e.getLat()]);
            });
            mouseTool.close(false);
            // console.log('lujing', e.obj.getPath()) //获取路径/范围
            // console.log('banjing', e.obj.getRadius()) //获取半径
            _this.radius = e.obj.getRadius().toFixed(0);
            // console.log('zhongxindian', e.obj.getCenter()) //获取中心点
            let centerLng = e.obj.getCenter().lng;
            let centerLat = e.obj.getCenter().lat;
            _this.center = [centerLng, centerLat];
            // 清除原来的圆
            map.clearMap();
            // 进入编辑模式
            var circle = new AMap.Circle({
              center: _this.center,
              radius: _this.radius, //半径
              borderWeight: 3,
              strokeColor: "#FF33FF",
              strokeOpacity: 1,
              strokeWeight: 6,
              strokeOpacity: 0.2,
              fillOpacity: 0.4,
              strokeStyle: "dashed",
              strokeDasharray: [10, 10],
              // 线样式还支持 'dashed'
              fillColor: "#1791fc",
              zIndex: 50,
            });
            map.add(circle);
            map.plugin(["AMap.CircleEditor"], function () {
              circleEditor = new AMap.CircleEditor(map, circle);
              circleEditor.open();
              let newLng = "";
              let newLat = "";
              let newRadius = "";
              let fenceData = {
                CIRCLE_LONG: centerLng + "",
                CIRCLE_LAT: centerLat + "",
                RADIUS: _this.radius + "",
              };
              circleEditor.on("move", function (lnglat) {
                // console.log(lnglat.lnglat.lng, lnglat.lnglat.lat) //调整后的圆心坐标
                fenceData.CIRCLE_LONG = lnglat.lnglat.lng.toFixed(6) + "";
                fenceData.CIRCLE_LAT = lnglat.lnglat.lat.toFixed(6) + "";
              });
              circleEditor.on("adjust", function (event) {
                // log.info('触发事件：adjust')
                // console.log(event.radius);//调整后的半径
                fenceData.RADIUS = event.radius.toFixed(2) + "";
              });
              circleEditor.on("end", function (event) {
                log.info("触发事件： end");
                // event.target 即为编辑后的圆形对象
              });
              // fenceData={
              //     CIRCLE_LONG: newLng,
              //     CIRCLE_LAT: newLat,
              //     RADIUS: newRadius
              //   }
              _this.fenceForm.fenceData = fenceData;
            });
            // 缩放地图到合适的视野级别
            map.setFitView([circle]);
            var circleEditor = new AMap.CircleEditor(map, circle);
          });
          // 矩形绘制
        } else if (type === "rectangle") {
          mouseTool.rectangle();
          AMap.event.addListener(mouseTool, "draw", function (e) {
            _this.fenceForm.coordinate = [];
            let path = e.obj.getPath();
            path.forEach((e) => {
              _this.fenceForm.coordinate.push([e.getLng(), e.getLat()]);
            });
            mouseTool.close(false);
            fenceData = [];
            // console.log('lujing', e.obj.getPath()) //获取路径/范围
            let fenceDataItem = {};
            e.obj.getPath().forEach((item) => {
              fenceDataItem = {
                LONG: item.lng + "",
                LAT: item.lat + "",
              };
              fenceData.push(fenceDataItem);
            });
            _this.fenceForm.fenceData = fenceData;
            // 清除原来的矩形
            map.clearMap();
            // 进入编辑模式
            var southWest = new AMap.LngLat(
              Number(fenceData[3].LONG).toFixed(3),
              Number(fenceData[3].LAT).toFixed(3)
            );
            var northEast = new AMap.LngLat(
              Number(fenceData[1].LONG).toFixed(3),
              Number(fenceData[1].LAT).toFixed(3)
            );
            var bounds = new AMap.Bounds(southWest, northEast);
            var rectangle = new AMap.Rectangle({
              bounds: bounds,
              borderWeight: 3,
              strokeColor: "#FF33FF",
              strokeOpacity: 1,
              strokeWeight: 6,
              strokeOpacity: 0.2,
              fillOpacity: 0.4,
              strokeStyle: "dashed",
              strokeDasharray: [10, 10],
              // 线样式还支持 'dashed'
              fillColor: "#1791fc",
              zIndex: 50,
            });
            map.add(rectangle);
            // 缩放地图到合适的视野级别
            map.plugin(["AMap.RectangleEditor"], function () {
              let rectangleEditor = new AMap.RectangleEditor(map, rectangle);
              rectangleEditor.open();
              let newPath = [];
              let fenceData = [
                {
                  LONG: "116.356",
                  LAT: "39.894",
                },
                {
                  LONG: "116.418",
                  LAT: "39.894",
                },
                {
                  LONG: "116.418",
                  LAT: "39.859",
                },
                {
                  LONG: "116.356",
                  LAT: "39.859",
                },
              ];
              let fenceDataItem = {};
              rectangleEditor.on("adjust", function (event) {
                log.info("触发事件：adjust");
                // console.log('northeast',event.Rd.northeast);
                let northeast = event.Rd.northeast;
                // console.log('southwest',event.Rd.southwest);
                let southwest = event.Rd.southwest;
                fenceData[0] = {
                  LONG: southwest.lng.toFixed(3) + "",
                  LAT: northeast.lat.toFixed(3) + "",
                };
                fenceData[1] = {
                  LONG: northeast.lng.toFixed(3) + "",
                  LAT: northeast.lat.toFixed(3) + "",
                };
                fenceData[2] = {
                  LONG: northeast.lng.toFixed(3) + "",
                  LAT: southwest.lat.toFixed(3) + "",
                };
                fenceData[3] = {
                  LONG: southwest.lng.toFixed(3) + "",
                  LAT: southwest.lat.toFixed(3) + "",
                };
                _this.fenceForm.fenceData = fenceData;
              });
              rectangleEditor.on("end", function (event) {
                log.info("触发事件： end");
                // event.target 即为编辑后的矩形对象
              });
              //   newPath.forEach(item => {
              //       fenceDataItem={
              //         LONG: item.lng+'',
              //         LAT: item.lat+''
              //       }
              //       fenceData.push(fenceDataItem)
              //     });
              _this.fenceForm.fenceData = fenceData;
            });
            // 缩放地图到合适的视野级别
            map.setFitView([rectangle]);
          });
          // 多边形绘制
        } else if (type === "polygon") {
          let map = amapManager.getMap();
          mouseTool.polygon();
          AMap.event.addListener(mouseTool, "draw", function (e) {
            _this.fenceForm.coordinate = [];
            let path = e.obj.getPath();
            path.forEach((e) => {
              _this.fenceForm.coordinate.push([e.getLng(), e.getLat()]);
            });
            mouseTool.close(false);
            // console.log('lujing', e.obj.getPath()) //获取路径/范围
            let fenceData = [];
            let fenceDataItem = {};
            e.obj.getPath().forEach((item) => {
              fenceDataItem = {
                LONG: item.lng + "",
                LAT: item.lat + "",
              };
              fenceData.push(fenceDataItem);
            });
            _this.fenceForm.fenceData = fenceData;
            // 清除原来的
            map.clearMap();
            // 引入多边形编辑器插件
            let paths = _this.fenceForm.coordinate;
            var polygon = new AMap.Polygon({
              path: paths,
              strokeColor: "#FF33FF",
              strokeWeight: 6,
              strokeOpacity: 0.2,
              fillOpacity: 0.4,
              fillColor: "#1791fc",
              zIndex: 50,
              bubble: true,
            });
            map.add([polygon]);
            map.setFitView();
            map.plugin(["AMap.PolyEditor"], function () {
              // 实例化多边形编辑器，传入地图实例和要进行编辑的多边形实例
              var polyEditor = new AMap.PolyEditor(map, polygon);
              // polyEditor.open()
              // 开启编辑模式
              polyEditor.open();
              polyEditor.on("adjust", function (event) {
                log.info("触发事件：adjust");
                let path = event.target.w.path;
                let pathData = {};
                let data = [];
                path.forEach((item) => {
                  for (let key in item) {
                    if (key === "lng") {
                      pathData.LANG = item[key] + "";
                    } else if (key === "lat") {
                      pathData.LAT = item[key] + "";
                    }
                  }
                  data.push(pathData);
                  pathData = {};
                });
                _this.fenceForm.fenceData = data;
              });
            });
          });
        }
      });
    },
    submit() {
      this.$emit("result", this.markers);
    },
  },
};
</script>

<style lang="scss" scoped></style>
